package udp;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/17
 * Time:15:07
 **/
public class Client {
    /**
     * 客户端-"智能"聊天机器人
     */
    //服务器IP
    private static final String ip = "127.0.0.1";
    //服务器端口号：
    private static final int port = 1001;
    //数据的最大值
    private static final int blen = 1024;

    public static void main(String[] args) throws IOException {
        //1.启动客户端
        DatagramSocket client = new DatagramSocket();//客户端不需要传端口号
        System.out.println("客户端已启动");
        //输入
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("我：");
            String msg = scanner.nextLine();
            //2.发送消息
            DatagramPacket clientPacket = new DatagramPacket(
                    msg.getBytes(),
                    msg.getBytes().length,
                    InetAddress.getByName(ip),
                    port
            );
            client.send(clientPacket);
            //3.接收服务器返回信息
            DatagramPacket serverPacket = new DatagramPacket(new byte[blen], blen);
            client.receive(serverPacket);
            String serMsg = new String(serverPacket.getData());
            System.out.println("对方：" + serMsg);
        }
    }
}
